package net.lab1024.sa.base.utils;

import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.domain.EventBaseAlert;
import org.mvel2.MVEL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Slf4j
public class MvelUtils {

    /**
            * 验证警报是否符合MVEL表达式条件
     * @param event EventBaseAlert事件对象
     * @param mvelExpr MVEL表达式字符串
     * @return 如果表达式执行成功且结果为布尔值true则返回true，否则返回false
     */
    public static boolean validateAlert(EventBaseAlert event, String mvelExpr) {
        try {
            // 直接用event对象作为上下文，MVEL可直接访问其属性
            Object result = MVEL.eval(mvelExpr, event);
            if (result instanceof Boolean) {
                return (Boolean) result;
            }
            return false;
        } catch (Exception e) {
            log.error("MVEL表达式执行异常：{}", e.getMessage(), e);
            return false;
        }
    }

    public static String checkAlert(EventBaseAlert event, String mvelExpr) {
        try {
            // 直接用event对象作为上下文，MVEL可直接访问其属性
            Object result = MVEL.eval(mvelExpr, event);
            if (result instanceof Boolean) {
                return result+"";
            }
            return "解析异常";
        } catch (Exception e) {
            log.error("MVEL表达式执行异常：{}", e.getMessage(), e);
            return  e.getMessage();
        }
    }
}